/**
 * 安装SpringMVC拦截器,该拦截器主要用来实现线程局部变量维护，例如当前用户等
 */
package com.cnfangmao.threadscope;

import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SuppressWarnings("deprecation")
@Configuration
public class ThreadScopeWEBMVCInterceptor extends WebMvcConfigurerAdapter {
//	private static Logger logger = Logger.getLogger(ThreadScopeWEBMVCInterceptor.class); 
	private static List<HandlerInterceptor> lstInterceptors=new LinkedList<HandlerInterceptor>();
	
	public static void AddInterceptor(HandlerInterceptor handler)
	{
		lstInterceptors.add(handler);
	}
	
	private static class InternalInterceptor implements HandlerInterceptor 
	{

		public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
				throws Exception {
			for(HandlerInterceptor interceptor:lstInterceptors)
			{
				interceptor.afterCompletion(arg0, arg1, arg2, arg3);
			}
		}

		public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
				throws Exception {
			// TODO Auto-generated method stub
			for(HandlerInterceptor interceptor:lstInterceptors)
			{
				interceptor.postHandle(arg0, arg1, arg2, arg3);
			}			
		}

		public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
			// TODO Auto-generated method stub
			for(HandlerInterceptor interceptor:lstInterceptors)
			{
				interceptor.preHandle(arg0, arg1, arg2);
			}
			return true;
		}
		
	}
	
	@Bean
	public InternalInterceptor getThreadInterceptor()
	{
		return new InternalInterceptor();
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getThreadInterceptor()).addPathPatterns("/**");
		super.addInterceptors(registry);
	}
}
